package com.itfreer.content.notice;

import android.util.Log;

import com.itfreer.content.GatherDatabaseHelper;
import com.itfreer.data.remote.DataService;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.misc.TransactionManager;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * 通知服务接口，用于数据同步与数据展示
 */
public class NoticeService {

    private static final String noticeSN = "gisnotice";
    // 只加载和同步最新的30条记录，其它信息在移动端加载无意
    private static final Integer pageSize = 30;

    public static final NoticeService instance = new NoticeService();
    private NoticeService() {
    }

    /**
     * 获取所有信息
     * @return
     */
    public List<NoticeEntity> getEntitys() {
        try {
            Dao<NoticeEntity, String> dao = GatherDatabaseHelper.getInstance().getDao(NoticeEntity.class);
            List<NoticeEntity> datas = dao.queryForAll();
            return datas;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 同步通知
     * @return
     */
    public Boolean syn() {
        //创建事务管理器
        TransactionManager transactionManager = new TransactionManager(GatherDatabaseHelper.getInstance().getConnectionSource());
        //一个调用的事件
        Callable<Boolean> callable  = new Callable<Boolean>() {
            //如果异常被抛出 事件管理 就知道保存数据失败要回滚
            @Override
            public Boolean call() throws Exception {
                Dao<NoticeEntity, String> dao = GatherDatabaseHelper.getInstance().getDao(NoticeEntity.class);
                // 清空表
                dao.queryRaw("delete from gather_notice");

                HashMap<String, Integer> order = new HashMap<>();
                order.put("publishDate", 1);
                List<NoticeEntity> datas = DataService.instance.getEntitys(noticeSN,null,null,order, pageSize, 1, NoticeEntity.class);
                if(datas!=null && datas.size()>0){
                    for(NoticeEntity item : datas){
                        dao.create(item);
                    }
                }
                return true;
            }
        };

        Boolean result;
        try {
            //执行事件
            result =  transactionManager.callInTransaction(callable);
        } catch (SQLException e) {
            result = false;
            Log.w("YKF","事务保存异常");
            e.printStackTrace();
        }
        return result;
    }
}
